package com.beetobe.main.schedule;

import java.io.IOException;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.TimeZone;

import android.os.AsyncTask;
import android.text.format.Time;
import android.util.Log;

import com.beetobe.callib.CalendarLibHelper;
import com.beetobe.callib.event.EventInfo;
import com.google.api.client.util.DateTime;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.calendar.model.Events;

public class AsyncCheckEvent extends AsyncTask<Void, Void, Void> {
	private String calendarId;
	private com.google.api.services.calendar.Calendar client;
	
	public AsyncCheckEvent(String calendarId){
		this.calendarId = calendarId;
		client = CalendarLibHelper.client;
	}
	@Override
	protected Void doInBackground(Void... arg0) {
		// TODO Auto-generated method stub
		try {

			com.google.api.services.calendar.model.Calendar calendar = client
					.calendars().get(calendarId).execute();
			Time now = new Time();
			now.setToNow();
			Events events = client.events().list(calendar.getId())
					.setTimeMin(getEventTime(-3))
					.setTimeMax(getEventTime(3))
					.execute();
			
			for (Event clientEvent : events.getItems()) {
				EventInfo info = new EventInfo(
						clientEvent.getId(),
						clientEvent.getSummary());

				StringTokenizer tokenizer = new StringTokenizer(
						info.toString(), "ㅫ");
				String date = tokenizer.nextToken();
				String idContent = tokenizer
						.nextToken();
				
				StringTokenizer dateToken = new StringTokenizer(date, ".");
				int year = Integer.parseInt(dateToken.nextToken());
				int month = Integer.parseInt(dateToken.nextToken());
				int day = Integer.parseInt(dateToken.nextToken());
				
				StringTokenizer idContentToken = new StringTokenizer(idContent, "]");
				String label = idContentToken.nextToken();
				String name = idContentToken.nextToken();
				
				if(label.equals("[GUEST")) {
					CalendarLibHelper.attendantList.add(new AttendantInfo(year, month, day, name));
				}
				if(label.equals("[ClientID")) {
					CalendarLibHelper.clientList.add(name);
				}
			}
		} catch (IOException e) {
			// activity.handleGoogleException(e);
		} finally {
			CalendarLibHelper.isEventChecked = true;
		}
		return null;
	}
	
	private DateTime getEventTime(int period){
		Time endTime = new Time();
		endTime.setToNow();
		endTime.month += period;
		endTime.normalize(true);
		Date makeDate = new Date(endTime.toMillis(false));
		DateTime makeDateTime = new DateTime(makeDate,TimeZone.getTimeZone("UTC"));
		return makeDateTime;
	}

}
